import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import http from '@/utils/http';
import { ElMessage } from 'element-plus';
import { useAppStore } from './app';


export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || null);
  const user = ref(JSON.parse(localStorage.getItem('user')) || null);
  const loading = ref(false);
  
  // 计算属性
  const isAuthenticated = computed(() => !!token.value);
  const userAvatar = computed(() => user.value?.avatar || '/default-avatar.png');
  const userName = computed(() => user.value?.username || '');
  const userId = computed(() => user.value?.user_id || '');
  const menuList = computed(() => user.value?.menu_list || []);
  const menuTree = computed(() => user.value?.menu_tree || []);

  const getMenuList = async() => { 

    const data = await http.get('/menus');
    console.log('获取菜单列表:', data);
    return data;
  }

  const getMenuTree = async () => {
    const data = await http.get('/menus/tree');
    console.log('获取菜单树:', data);
    return data;
  }
  
  // 登录方法
  const login = async (loginForm) => {
    loading.value = true;
    try {
      console.log('发送登录请求:', loginForm);
      const data = await http.post('/auth/login', loginForm);
      
      console.log('登录请求响应:', data);
      
      // 确保返回的数据符合预期
      if (!data || !data.access_token || !data.user_info) {
        throw new Error('登录响应数据格式错误');
      }

      // 设置http请求头
      http.defaults.headers.common['Authorization'] = `Bearer ${data.access_token}`;
      
      // 如果使用了响应拦截器，这里已经是data部分
      const { access_token, user_info } = data;
      const menuList = await getMenuList()
      user_info.menu_list = menuList;
      const menuTree = await getMenuTree();
      user_info.menu_tree = menuTree;

      // 存储token和用户信息
      setToken(access_token);
      setUser(user_info);
      
      console.log('登录成功，用户信息已保存');
      ElMessage.success('登录成功');
      return true;
    } catch (error) {
      console.error('登录失败:', error);
      ElMessage.error(error.message || '登录失败，请重试');
      return false;
    } finally {
      loading.value = false;
    }
  };

  // OAuth登录方法
  const loginWithToken = async (accessToken) => {
    loading.value = true;
    try {
      // 如果 token 还没有设置，则设置它
      if (!token.value || token.value !== accessToken) {
        setToken(accessToken);
      }
      
      console.log('获取用户信息，当前 token:', token.value);
      http.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
      console.log('Authorization 头:', http.defaults.headers.common['Authorization']);
      
      // 获取用户信息
      const response = await http.get('/auth/user');
      
      console.log('获取用户信息响应:', response);
      
      if (!response || !response.user_info) {
        throw new Error('获取用户信息失败');
      }
      
      // 存储用户信息
      const { user_info } = response;
      const menuList = await getMenuList()
      user_info.menu_list = menuList;
      const menuTree = await getMenuTree();
      user_info.menu_tree = menuTree;
      setUser(user_info);
      ElMessage.success('登录成功');
      return true;
    } catch (error) {
      console.error('OAuth登录失败:', error);
      ElMessage.error(error.message || 'OAuth登录失败，请重试');
      logout();
      return false;
    } finally {
      loading.value = false;
    }
  };
  
  // 设置Token
  const setToken = (value) => {
    token.value = value;
    if (value) {
      localStorage.setItem('token', value);
      http.defaults.headers.common['Authorization'] = `Bearer ${value}`;
    } else {
      localStorage.removeItem('token');
      delete http.defaults.headers.common['Authorization'];
    }
  };
  
  // 设置用户信息
  const setUser = (value) => {
    user.value = value;
    if (value) {
      localStorage.setItem('user', JSON.stringify(value));
    } else {
      localStorage.removeItem('user');
    }
  };
  
  // 登出方法
  const logout = () => {
    setToken(null);
    setUser(null);
    useAppStore().clearState();
    ElMessage.success('已退出登录');
  };
  
  // 检查认证状态
  const checkAuth = () => {
    const storedToken = localStorage.getItem('token');
    const storedUser = localStorage.getItem('user');
    
    if (storedToken && storedUser) {
      try {
        setToken(storedToken);
        setUser(JSON.parse(storedUser));
        return true;
      } catch (error) {
        console.error('解析存储的用户信息失败:', error);
        logout();
        return false;
      }
    }
    return false;
  };
  
  return {
    // 状态
    token,
    user,
    loading,
    
    // 计算属性
    isAuthenticated,
    userAvatar,
    userName,
    userId,
    menuList,
    menuTree,
    
    // 方法
    login,
    loginWithToken,
    logout,
    checkAuth,
    setToken,
    setUser
  };
}); 